﻿using System;
using System.Collections.Generic;
using DrinkCounter;

namespace DrinkcounterUi
{
    public class ToniProtocol : IProtocol
    {
        private DrinkCounterClient _client;

        public ToniProtocol()
        {
            _client = new DrinkCounterClient(Properties.Settings.Default.PartyId);
        }

        public List<Person> GetPersons()
        {
            IList<Participant> participants = _client.GetParticipants();
            List<Person> persons = new List<Person>();

            foreach (var participant in participants)
            {
                persons.Add(new Person(participant.Id)
                {
                    Alcohol = participant.Promilles,
                    Name = participant.Name,
                    Drinks = participant.DrinkCount,
                    Idletime = GetIdleTimeFromParticipant(participant)
                });
            }
            return persons;
        }

        public void AddDrink(string id)
        {
            _client.AddDrink(new Participant() {Id = id});
        }

        private static string GetIdleTimeFromParticipant(Participant participant)
        {
            if (participant.DrinkCount == 0)
                return "";

            Drink latest = null;

            foreach (var drink in participant.Drinks)
            {
                if (latest == null)
                    latest = drink;
                else
                {
                    if (latest.TimeStamp < drink.TimeStamp)
                        latest = drink;
                }
            }

            // commented row prints the time of the last drink
            // return latest.TimeStamp.ToString("HH:mm");

            var span = (DateTime.Now - latest.TimeStamp);
            return ((int)span.TotalHours).ToString() + ":" + span.ToString("mm");
        }

    }
}